# -*- coding: utf-8 -*-
from flask import Blueprint, request, jsonify, make_response, redirect, g
from common.models.User import User
from common.libs.UrlManager import UrlManager
from common.libs.user.UserService import UserService
from common.libs.Helper import ops_render
from application import app, db
import json

''' 注册蓝图 '''
route_user = Blueprint('user_page', __name__)


@route_user.route("/login", methods=['GET', 'POST'])
def login():

    # GET 方法进行定义
    if request.method == "GET":
        return ops_render("user/login.html")

    # 定义全局msg变量
    resp = {'code': 200, 'msg': '登录成功~~', 'data': {}}
    req = request.values
    login_name = req['login_name'] if 'login_name' in req else ''
    login_pwd = req['login_pwd'] if 'login_pwd' in req else ''

    # 判断用户名的长度和空值
    if login_name is None or len(login_name) < 1:
        resp['code'] = -1
        resp['msg'] = "请输入正确的登陆用户名和密码！"
        return jsonify(resp)

    # 判断密码的长度和空值
    if login_pwd is None or len(login_pwd) < 1:
        resp['code'] = -1
        resp['msg'] = "请输入正确的登陆用户名和密码！!"
        return jsonify(resp)

    # 数据库中查询出账号进行判断
    user_info = User.query.filter_by(login_name=login_name).first()
    if not user_info:
        resp['code'] = -1
        resp['msg'] = "请输入正确的登陆用户名和密码！"
        return jsonify(resp)

    # 数据库中查出密码进行判断 密码经过加密函数genePwd进行处理过后的
    if user_info.login_pwd != UserService.genePwd(login_pwd, user_info.login_salt):
        resp['code'] = -1
        resp['msg'] = "请输入正确的登陆用户名和密码！"
        return jsonify(resp)

    if user_info.status != 1:
        resp['code'] = -1
        resp['msg'] = "账号已被禁用，请联系管理员！"
        return jsonify(resp)

    # 使用cook，并设置cookie 返回给浏览器
    app.logger.info(resp)
    response = make_response(json.dumps(resp))
    response.set_cookie(app.config['AUTH_COOKIE_NAME'], "%s#%s" % (UserService.geneAuthCode(user_info), user_info.uid))

    return response


@route_user.route("/edit", methods=['GET', 'POST'])
def edit():
    if request.method == 'GET':
        return ops_render("user/edit.html")

    resp = {'code': 200, 'msg': '操作成功！', 'data': {}}
    req = request.values

    nickname = req['nickname'] if 'nickname' in req else ''
    email = req['email'] if 'email' in req else ''

    if nickname is None or len(nickname) < 1:
        resp['code'] = -1
        resp['msg'] = '请输入符合规范的姓名~'
        return jsonify(resp)

    if email is None or len(email) < 1:
        resp['code'] = -1
        resp['msg'] = '请输入符合规范的邮箱地址~'
        return jsonify(resp)

    user_info = g.current_user
    user_info.nickname = nickname
    user_info.email = email

    db.session.add(user_info)
    db.session.commit()
    return jsonify(resp)


@route_user.route("/reset-pwd", methods=['GET', 'POST'])
def resetPwd():

    if request.method == 'GET':
        return ops_render("user/reset_pwd.html")

    resp = {'code': 200, 'msg': '操作成功', 'data': {}}
    req = request.values

    old_password = req['old_password'] if 'old_password' in req else ''
    new_password = req['new_password'] if 'new_password' in req else ''

    if old_password is None or len(old_password) < 6:
        resp['code'] = -1
        resp['msg'] = '请输入六位原始密码~'
        return jsonify(resp)

    if new_password is None or len(new_password) < 6:
        resp['code'] = -1
        resp['msg'] = '请输入六位新密码~'
        return jsonify(resp)

    if new_password == old_password:
        resp['code'] = -1
        resp['msg'] = '原始密码和新密码相同！请重新录入~'
        return jsonify(resp)

    user_info = g.current_user
    user_info.login_pwd = UserService.genePwd(new_password, user_info.login_salt)

    # 数据库进行提交
    db.session.add(user_info)
    db.session.commit()
    return jsonify(resp)


@route_user.route("/logout")
def logout():
    respone = make_response(redirect(UrlManager.buildUrl("/user/login")))
    respone.delete_cookie(app.config['AUTH_COOKIE_NAME'])
    return respone